package com.iyundao.io.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.iyundao.io.Service.PartymemberService;
import com.iyundao.io.model.PartyMember;
import com.iyundao.io.model.SysUserProvider;
import com.iyundao.io.tools.PartymemberVo;
import com.iyundao.io.tools.ResponseData;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/partymember")
public class PartymemberController {

    @Autowired
    private PartymemberService partymemberService;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @ApiOperation(value="批量添加人员", notes="批量添加人员")
    @RequestMapping(value = "/batchinsert", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData batchInsert(MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseData(0,"上传文件失败，请选择文件");
        }

        //获取文件名
        String fileName = String.valueOf(System.currentTimeMillis())+".xls";

        //文件路径
        File dest = new File(uploadFolder +"file/"+ fileName);

        if(!dest.exists()){
            //先得到文件的上级目录，并创建上级目录，在创建文件
            dest.getParentFile().mkdirs();
            try {
                //创建文件
                dest.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            //文件上传
            file.transferTo(dest);

            FileInputStream fis = new FileInputStream(dest);//文件流对象
            Workbook sheets = new HSSFWorkbook(fis);

            //读取Excel表格信息
            Sheet sheet = sheets.getSheetAt(0);//读取sheet 0

            int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名，所以不读
            int lastRowIndex = sheet.getLastRowNum();

            List<PartymemberVo> list = null;
            for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
                Row row = sheet.getRow(rIndex);
                if (row != null) {
                    /**
                     * 0:partymembername
                     * 1:partymembersex
                     * 2:partymemberbirthday
                     * 3:partymemberjointime
                     * 4:partymemberphone
                     * 5:partymemberaddress
                     * 6.jointime
                     */
                    PartymemberVo partyMember = new PartymemberVo();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    partyMember.setPartymembername(row.getCell(0).toString());
                    partyMember.setPartymembersex(row.getCell(1).toString());
                    //时间格式转换
                    Date date = simpleDateFormat.parse(row.getCell(2).toString());
                    partyMember.setPartymemberbirthday(date);
                    Date date1 = simpleDateFormat.parse(row.getCell(3).toString());
                    partyMember.setPartymemberjointime(date1);
                    partyMember.setPartymemberphone(row.getCell(4).toString());
                    partyMember.setPartymemberaddress(row.getCell(5).toString());
                    Date date2 = simpleDateFormat.parse(row.getCell(6).toString());
                    partyMember.setJointime(date2);

                    list.add(partyMember);
                }
            }
            SysUserProvider sysUser = (SysUserProvider) SecurityUtils.getSubject().getPrincipal();
            String sid = sysUser.getSysDept().getSid();
            return partymemberService.batchInsert(list,sid);

        } catch (IOException e) {
            return new ResponseData(0,e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResponseData(0,e.getMessage());
        }
    }

    @ApiOperation(value="单个添加人员", notes="单个添加人员")
    @RequestMapping(value = "/insert", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData insert(@RequestBody JSONObject parmas) {
        PartymemberVo partymemberVo = JSON.toJavaObject(parmas, PartymemberVo.class);
        SysUserProvider sysUser = (SysUserProvider) SecurityUtils.getSubject().getPrincipal();
        String sid = sysUser.getSysDept().getSid();
        return partymemberService.insert(partymemberVo, sid);
    }

    @ApiOperation(value="转出操作", notes="转出操作")
    @RequestMapping(value = "/rollout", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData rollOut(@RequestBody JSONObject parmas) {
        Integer organizationid = JSON.toJavaObject(parmas, Integer.class);
        return partymemberService.rollOut(organizationid);
    }

    @ApiOperation(value="根据id进行查询", notes="根据id进行查询")
    @RequestMapping(value = "/selectbyid", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectById(@RequestBody JSONObject parmas) {
        Integer id = JSON.toJavaObject(parmas, Integer.class);
        return partymemberService.selectById(id);
    }

    @ApiOperation(value="修改党员信息", notes="修改党员信息")
    @RequestMapping(value = "/updatepartymember", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData updatePartymember(@RequestBody JSONObject parmas) {
        PartyMember partyMember = JSON.toJavaObject(parmas, PartyMember.class);
        return partymemberService.updatePartymember(partyMember);
    }

    @ApiOperation(value="根据组织id查询人员", notes="根据组织id查询人员")
    @RequestMapping(value = "/selectpeoplebyorganizationid", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectByOrganizationId(){
        SysUserProvider sysUser = (SysUserProvider) SecurityUtils.getSubject().getPrincipal();
        String sid = sysUser.getSysDept().getSid();
        return partymemberService.selectByOrganizationId(sid);
    }
}
